<?php
/**
 * Note: 钉钉群通知, 设置不同的关键词进行消息拦截
 */
namespace App\Services;

use Illuminate\Support\Facades\Http;

class NoticeDingDingService
{
    /**
     * @param string $url
     * @param array $body
     */
    protected static function requestPost(string $url, array $body = [])
    {
        try {
            $response = Http::retry(1, 300)->timeout(5)->post($url, $body);
            $response->throw();
            info(__METHOD__, [$body, $response]);
        } catch (\Exception $e) {
            report($e);
        }
    }

    /**
     * @param string $url
     * @param array $body
     * @param bool $afterResponse
     */
    protected static function requestJob(string $url, array $body = [], bool $afterResponse = true)
    {
        $job = dispatch(function() use ($url, $body) {
            self::requestPost($url, $body);
        });
        if (!app()->runningInConsole() && $afterResponse) $job->afterResponse();
    }

    /**
     * @param string $message
     * @return string
     */
    private static function makeContent(string $message): string
    {
        $appName = config('app.name');
        $env = config('app.env');
        $nodeId = adminNodeId();

        return "[{$appName}][{$env}][节点 {$nodeId}] {$message}";
    }

    /**
     * 管理员
     * @param string $message
     * @param bool $afterResponse
     */
    public static function sendText(string $message, bool $afterResponse = true)
    {
        $url = config('admin.dingding_admin');
        if (!$url) {
            info("未配置钉钉通知地址: ". __METHOD__);
            return ;
        }
        $body = [
            'msgtype' => 'text',
            'text' => [
                'content' => self::makeContent($message),
            ],
        ];
        self::requestJob($url, $body, $afterResponse);

        // 同步发到通知群
        self::sendTextOperate($message, $afterResponse);
    }

    /**
     * 开发
     * @param string $message
     * @param bool $afterResponse
     */
    public static function sendTextDev(string $message, bool $afterResponse = true)
    {
        $url = config('admin.dingding_developer');
        if (!$url) {
            info("未配置钉钉通知地址: ". __METHOD__);
            return ;
        }
        $body = [
            'msgtype' => 'text',
            'text' => [
                'content' => self::makeContent("警告: {$message}"),
            ],
        ];
        self::requestJob($url, $body, $afterResponse);
    }

    /**
     * 运营
     * @param string $message
     * @param bool $afterResponse
     */
    public static function sendTextOperate(string $message, bool $afterResponse = true)
    {
        $url = config('admin.dingding_operate');
        if (!$url) {
            info("未配置钉钉通知地址: ". __METHOD__);
            return ;
        }
        $body = [
            'msgtype' => 'text',
            'text' => [
                'content' => self::makeContent($message),
            ],
        ];

        self::requestJob($url, $body, $afterResponse);
    }
}
